//
//  ViewController.m
//  ParserXML
//
//  Created by 移云 on 2019/10/16.
//  Copyright © 2019 admin. All rights reserved.
//

/*
 XML - Extentsible Markup Luanguage (可扩展标记语言)
 
 非常类似于HTML（超文本标记语言），HTML是用于显示数据，XML的目的是存储和传输数据
 
 XML是以前各种应用传输数据最常见的格式
 
 
 解析方法： - SAX方式（只读，速度快）
 1.开始解析xml
 2.找开始节点
 3.找到节点内容
 4.找到结束节点
 5.结束解析xml
 
 */

#import "ViewController.h"
#import "VideoModel.h"
@interface ViewController ()<NSXMLParserDelegate>

@property(nonatomic,strong)NSMutableArray *arrayM;
@property(nonatomic,strong)NSMutableString *mString;
@property(nonatomic,strong)VideoModel *currentVideo;
@end

@implementation ViewController

//懒加载
- (NSMutableArray *)arrayM
{
    if (_arrayM == nil)
    {
        _arrayM = [NSMutableArray arrayWithCapacity:10];
    }
    return _arrayM;
}

//懒加载
- (NSMutableString *)mString
{
    if (_mString == nil)
    {
        _mString = [NSMutableString string];
    }
    return _mString;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getXMLDateParserWithJSON];
}
#pragma mark - 字符串解析XML
- (void)getXMLDateParserWithJSON
{
        //该地址尽管是XML数据，但是请求返回的是个字典
        NSURL *url = [NSURL URLWithString:@"http://kjtt.wokeji.com/index/push-arcs?access-token=KzYDcKOAPkM4b2snv2EHdstYrkTLTw6u&page=2&sort=1"];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15];
        [request setValue:@"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Mobile Safari/537.36" forHTTPHeaderField:@"User-Agent"];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@",str);

            // 将字符串转换成字典
            NSData * getJsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary * getDict = [NSJSONSerialization JSONObjectWithData:getJsonData options:NSJSONReadingMutableContainers error:NULL];
            
            NSLog(@"%@",getDict[@"data"][0][@"id"]);
        }];

   
    
}

#pragma mark - SAX方法解析XML
- (void)parserXMLWithSAX
{

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/videos.xml"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15];
    [request setValue:@"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Mobile Safari/537.36" forHTTPHeaderField:@"User-Agent"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        NSXMLParser *xml = [[NSXMLParser alloc]initWithData:data];
        xml.delegate = self;    //在当前队列的线程上执行
        [xml parse];
        
    }];
}

#pragma mark - 代理方法
//1.开始解析
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
    NSLog(@"1.开始解析");
}

//2.找开始节点
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict
{
    //elementName - 节点名称
    //attributeDict - 标签的属性
    NSLog(@"2.找开始节点%@------属性%@",elementName,attributeDict);
    if ([elementName isEqualToString:@"video"])
    {
        self.currentVideo = [[VideoModel alloc]init];
        self.currentVideo.videoId = @([attributeDict[@"videoId"] intValue]);
        
        //添加到数组中
        [self.arrayM addObject:self.currentVideo];
    }
}

//3.找节点之间的内容
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    NSLog(@"3.找节点之间的内容%@",string);
    [self.mString appendString:string];
}

//4.找到到结束节点
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    NSLog(@"4.找到到结束节点%@",elementName);
    //判断标签是否是对应的属性
    {
//    if([elementName isEqualToString:@"name"])
//    {
//        self.currentVideo.name = self.mString;
//    }else if([elementName isEqualToString:@"length"]){
//        self.currentVideo.length = @(self.mString.intValue);
//    }else if([elementName isEqualToString:@"videoURL"]){
//        self.currentVideo.videoURL = self.mString;
//    }else if([elementName isEqualToString:@"imageURL"]){
//        self.currentVideo.imageURL = self.mString;
//    }else if([elementName isEqualToString:@"desc"]){
//        self.currentVideo.desc = self.mString;
//    }else if([elementName isEqualToString:@"teacher"]){
//        self.currentVideo.teacher = self.mString;
//    }
    }
    
    //简化代码
    if (![elementName isEqualToString:@"video"] && ![elementName isEqualToString:@"videos"]) {
        
        //kvc 赋值，只是把地址赋值给属性，不会做类型转换，当出现可变数据时，容易出错
        //所以，在网络中，数据类型基本都使用copy
        [self.currentVideo setValue:self.mString forKey:elementName];
    }
    //清空可变字符串
    [self.mString setString:@""];
}

//5.结束解析
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
    NSLog(@"5.结束解析");
    NSLog(@"%@",self.arrayM);
}

//6.解析错误
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
    NSLog(@"解析出错 %@",parseError);
}



@end
